package cn.briarbear.myblog.repository;

import cn.briarbear.myblog.entity.table.Blog;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@CacheConfig(cacheNames = "blog")  //这个相等于指定了该接口下所有方法统一的缓存结果集名
public interface BlogRepository extends JpaRepository<Blog,Integer> {

//    @Cacheable(cacheNames = "blogId")  //将缓存在以blogId命名的集中
    @Cacheable
    Optional<Blog> findById(Integer id);

//    @Cacheable
    List<Blog> findAll();

    @CachePut(key = "#result.id")
    Blog save(Blog blog);

//    @Cacheable
    List<Blog> findByTitleContainingOrIntroductionContaining(String title,String introduction);

//    @Cacheable
    @Query(value = "select b from Blog b where b.id in (select tb.blogId from TagBlog tb where tb.tagId=?1)")
    List<Blog> findByTagId(Integer tagId);

    @Modifying
    @Transactional
    @CacheEvict(key = "#p0")
    void deleteById(Integer id);

}
